package com.yxw.live_vod_boot.jobs;

import com.yxw.live_vod_boot.utils.RedisManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.yxw.live_vod_boot.vo.CheckLiveIsActiveVO;
import com.yxw.live_vod_facade.vo.LivePushStreamRedisCacheVO;
import com.yxw.live_vod_boot.cache.QueueCache;
import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import com.yxw.live_vod_boot.service.impl.LiveProcessServiceImpl;
import com.yxw.live_vod_boot.service.impl.LiveSysManagerProcessServiceImpl;
import org.springframework.scheduling.annotation.Async;
import com.yxw.yxnet_cd_center.common.utils.BaseResult;
import java.util.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.yxw.live_vod_boot.utils.JsonUtils;
import com.yxw.live_vod_boot.utils.RedisPipeAccessObject;
import com.yxw.live_vod_boot.vo.LiveOnlineInRedisCacheVO;
import com.yxw.live_vod_facade.constant.LiveShopConstant;
import com.yxw.live_vod_facade.enums.LiveStateEnum;
import java.util.List;
import java.util.ArrayList;
/*** 
 * 用于当前服务器的延时任务
*@author hjx
*@date 2023/12/1 14:06:22
*@update 2023/12/14 14:06:22
*
**/
@Slf4j
@Component
@EnableScheduling
public class LiveDelayJobs {
    
    @Autowired
    private RedisManager oRedisManager;
    
    @Autowired
    private LiveProcessServiceImpl oLiveProcessServiceImpl;
    
    @Autowired
    private LiveSysManagerProcessServiceImpl oLiveManagerProcessServiceImpl;
    @Autowired
    private QueueCache oQueueCache;
    
    private static int checkScheduledState = 0;
    /**
     * 检查直播推流日志是否中断以及异常计费，并删除对应的Redis
     */
    @Async
    @Scheduled(fixedRate = 50)
    public void delayJob()
    {
        if(!QueueCache.serviceIsOk())
        {
            return;
        }
        if(null == QueueCache.getCheckLiveIsActiveDelayQueue())
        {
            System.out.println("QueueCache.getCheckLiveIsActiveDelayQueue() is null");
            return;
        }
        if(checkScheduledState == 0)
        {
            System.out.println("delayJob first time start at:" + System.currentTimeMillis());
        }
        CheckLiveIsActiveVO oCheckLiveIsActiveVO = oQueueCache.delayCheckLiveIsActivePoll();//QueueCache.getCheckLiveIsActiveDelayQueue().poll();
        if(null != oCheckLiveIsActiveVO)
        {
            Integer iExecCount;
            Object oObject;
            //QueueCache.getCheckLiveIsActiveCHM().remove(oCheckLiveIsActiveVO.getMapKey());
            LivePushStreamRedisCacheVO oLivePushStreamRedisCacheVO; 
            //oLiveRedisCacheVO = (LivePushStreamRedisCacheVO)oRedisManager.get(oCheckLiveIsActiveVO.getRedisKey()); 
            switch (oCheckLiveIsActiveVO.getCheckType())
            {
                case 0:
                    System.out.println("delayJob---------------------------------------------------------------------------------------------------------------------case 0");
                    System.out.println("oCheckLiveIsActiveVO:" );
                    System.out.println(JsonUtils.toJson(oCheckLiveIsActiveVO).toString());
                    System.out.println("oCheckLiveIsActiveVO.getRedisKey():" + oCheckLiveIsActiveVO.getRedisKey());
                    //延时检查推流状态
                    oObject = oRedisManager.get(oCheckLiveIsActiveVO.getRedisKey()); 
                    System.out.println("oObject:");
                    System.out.println(oObject);
                    if(ObjectUtil.isEmpty(oObject))
                    {
                        return;
                    }  
                    oLivePushStreamRedisCacheVO = (LivePushStreamRedisCacheVO)oObject;//(LivePushStreamRedisCacheVO)oRedisManager.get(oCheckLiveIsActiveVO.getRedisKey()); 
                    if(ObjectUtil.isEmpty(oLivePushStreamRedisCacheVO))
                    {
                        return;
                    }                    
                    Long now = System.currentTimeMillis();
                    Long iTime = now - oLivePushStreamRedisCacheVO.getLastPushLogTime();
                    
                    
                    System.out.println("oLivePushStreamRedisCacheVO:");
                    System.out.println(oLivePushStreamRedisCacheVO);
                    System.out.println("now:" + now);
                    System.out.println("oLivePushStreamRedisCacheVO.getLastPushLogTime():" + oLivePushStreamRedisCacheVO.getLastPushLogTime());
                    System.out.println("now - oLivePushStreamRedisCacheVO.getLastPushLogTime():" + iTime);
                    if(iTime >= 90000)
                    { 
                        
                        oLivePushStreamRedisCacheVO.setInterruptedCount(oLivePushStreamRedisCacheVO.getInterruptedCount() + 1);
                        //oLivePushStreamRedisCacheVO.setLiveState(LiveStateEnum.LIVE_STOP.getCode());
                        //oRedisManager.set(oCheckLiveIsActiveVO.getRedisKey(), oLivePushStreamRedisCacheVO);
                    //} 
                    //else
                    //{
                        List<RedisPipeAccessObject> sourceList = new ArrayList();
                        RedisPipeAccessObject oRedisPipeAccessObject = null;
                        String redisKey = oCheckLiveIsActiveVO.getRedisKey();//LiveShopConstant.LIVE_SHOP_ONLINELIVE_SHOPIDKEY_HASH_REDISKEY;
                        LiveOnlineInRedisCacheVO oLiveOnlineInRedisCacheVO = (LiveOnlineInRedisCacheVO)oRedisManager.getMapValue(redisKey, oLivePushStreamRedisCacheVO.getLiveShopId().toString());
                        if(null != oLiveOnlineInRedisCacheVO)
                        {
                            
                            if(oLiveOnlineInRedisCacheVO.getLiveId().trim().toLowerCase().equals(oLivePushStreamRedisCacheVO.getLiveId().trim().toLowerCase()))
                            {
                                oRedisPipeAccessObject = RedisPipeAccessObject.getDelMapObject(redisKey, oLivePushStreamRedisCacheVO.getLiveShopId().toString());
                                sourceList.add(oRedisPipeAccessObject);
                            }
                            redisKey = LiveShopConstant.LIVE_SHOP_ONLINELIVE_HASH_REDISKEY;
                            oRedisPipeAccessObject = RedisPipeAccessObject.getDelMapObject(redisKey, oLivePushStreamRedisCacheVO.getLiveId());
                            sourceList.add(oRedisPipeAccessObject);             
                            
                        }                        
                        //oRedisPipeAccessObject = RedisPipeAccessObject.getAddObject(oCheckLiveIsActiveVO.getRedisKey(), oLivePushStreamRedisCacheVO);
                        //sourceList.add(oRedisPipeAccessObject); 
                        oRedisPipeAccessObject = RedisPipeAccessObject.getAddObject(LiveShopConstant.LIVE_SHOP_ONLINELIVE_SHOPIDKEY_HASH_REDISKEY.concat(oLivePushStreamRedisCacheVO.getLiveId()), LiveStateEnum.LIVE_STOP.getCode());
                        sourceList.add(oRedisPipeAccessObject);   
                        oRedisManager.multiAccessByPipe(sourceList);
                    }
                    break;
                case 1:
                    System.out.println("delayJob---------------------------------------------------------------------------------------------------------------------case 1");
                    System.out.println("oCheckLiveIsActiveVO:" );
                    System.out.println(JsonUtils.toJson(oCheckLiveIsActiveVO).toString());
                    System.out.println("oCheckLiveIsActiveVO.getRedisKey():" + oCheckLiveIsActiveVO.getRedisKey());                    
                    //延时计费扣款
                    oObject = oRedisManager.get(oCheckLiveIsActiveVO.getRedisKey()); 
                    if(null== oObject)
                    {
                        return;
                    }  
                    oLivePushStreamRedisCacheVO = (LivePushStreamRedisCacheVO)oObject;//(LivePushStreamRedisCacheVO)oRedisManager.get(oCheckLiveIsActiveVO.getRedisKey()); 
                    if(ObjectUtil.isEmpty(oLivePushStreamRedisCacheVO))
                    {
                        return;
                    }                
                    BaseResult oBaseResult = oLiveProcessServiceImpl.serverEndLive(oLivePushStreamRedisCacheVO.getLiveId(),oLivePushStreamRedisCacheVO);
                    if(oBaseResult.isResult())
                    {                        
                        oRedisManager.del(oCheckLiveIsActiveVO.getRedisKey());
                    }
                    else
                    {
                        //执行失败重启任务
                        if(null == oCheckLiveIsActiveVO.getExecCount())
                        {
                            iExecCount = 0;
                        }
                        else
                        {
                            iExecCount = oCheckLiveIsActiveVO.getExecCount();
                        }
                        iExecCount = iExecCount + 1;
                        Long delayTime = 60000L * iExecCount;
                        delayTime = System.currentTimeMillis() + delayTime;
                        String mapKey = oCheckLiveIsActiveVO.getRedisKey() + "_" + UUID.randomUUID().toString().replaceAll("-", "");
                        oCheckLiveIsActiveVO = new CheckLiveIsActiveVO();
                        oCheckLiveIsActiveVO.InIt(oCheckLiveIsActiveVO.getRedisKey(),mapKey,delayTime,1);
                        oCheckLiveIsActiveVO.setExecCount(iExecCount);
                        oQueueCache.delayCheckLiveIsActivePut(oCheckLiveIsActiveVO);
                    }   
                    break;
                case 2:
                    //罚款时费用不够,禁用直播流
                    oLivePushStreamRedisCacheVO = (LivePushStreamRedisCacheVO)oRedisManager.get(oCheckLiveIsActiveVO.getRedisKey()); 
                    oLiveManagerProcessServiceImpl.managerDeductFeeForbidStream(oCheckLiveIsActiveVO,oLivePushStreamRedisCacheVO);
                    break;
                case 3:
                    //延时解除中断(以分钟计)
                    oLivePushStreamRedisCacheVO = (LivePushStreamRedisCacheVO)oRedisManager.get(oCheckLiveIsActiveVO.getRedisKey()); 
                    BaseResult resumeStopBaseResult = oLiveManagerProcessServiceImpl.managerDelayResumeStop(oCheckLiveIsActiveVO,oLivePushStreamRedisCacheVO);
                    if(!resumeStopBaseResult.isResult())
                    {
                        //执行失败重启任务,失败后强制执行20次
                        if(null == oCheckLiveIsActiveVO.getExecCount())
                        {
                            iExecCount = 0;
                        }
                        else
                        {
                            iExecCount = oCheckLiveIsActiveVO.getExecCount();
                        }
                        if(20<iExecCount)
                        {
                            iExecCount = iExecCount + 1;
                            Long delayTime = 60000L * iExecCount;
                            delayTime = System.currentTimeMillis() + delayTime;
                            String mapKey = oCheckLiveIsActiveVO.getRedisKey() + "_" + UUID.randomUUID().toString().replaceAll("-", "");
                            oCheckLiveIsActiveVO = new CheckLiveIsActiveVO();
                            oCheckLiveIsActiveVO.InIt(oCheckLiveIsActiveVO.getRedisKey(),mapKey,delayTime,3);
                            oCheckLiveIsActiveVO.setExecCount(iExecCount);
                            oQueueCache.delayCheckLiveIsActivePut(oCheckLiveIsActiveVO);
                        }
                    }
                    break; 
                case 4:
                    //延时解除禁播(以天计)，恢复正常状态
                    BaseResult resumeLimitBaseResult =oLiveManagerProcessServiceImpl.managerDelayResumeLimit(oCheckLiveIsActiveVO);
                    if(!resumeLimitBaseResult.isResult())
                    {
                        //执行失败重启任务,失败后强制执行20次
                        if(null == oCheckLiveIsActiveVO.getExecCount())
                        {
                            iExecCount = 0;
                        }
                        else
                        {
                            iExecCount = oCheckLiveIsActiveVO.getExecCount();
                        }
                        if(20<iExecCount)
                        {
                            iExecCount = iExecCount + 1;
                            Long delayTime = 60000L * iExecCount;
                            delayTime = System.currentTimeMillis() + delayTime;
                            String mapKey = oCheckLiveIsActiveVO.getRedisKey() + "_" + UUID.randomUUID().toString().replaceAll("-", "");
                            oCheckLiveIsActiveVO = new CheckLiveIsActiveVO();
                            oCheckLiveIsActiveVO.InIt(oCheckLiveIsActiveVO.getRedisKey(),mapKey,delayTime,4);
                            oCheckLiveIsActiveVO.setExecCount(iExecCount);
                            oQueueCache.delayCheckLiveIsActivePut(oCheckLiveIsActiveVO);
                        }
                    }
                    break;     
                default:
                    break;
            }
        }
        if(checkScheduledState == 0)
        {
            System.out.println("delayJob first time end at:" + System.currentTimeMillis());
            checkScheduledState = 1;
        }
    }
    /*
    @Async
    @Scheduled(fixedRate = 1800000)
    public void saveQueue()
    {
        Cache livePushActiveCache = QueueCache.getLivePushActiveCache();
        if(null != livePushActiveCache)
        {  
            livePushActiveCache.put(new Element(QueueCache.getLivePushActiveCacheName(), QueueCache.getCheckLiveIsActiveDelayQueue()));
        } 
        Cache oLiveWatchLogCache = QueueCache.getLiveWatchLogCache();
        if(null != oLiveWatchLogCache)
        {
            oLiveWatchLogCache.put(new Element(QueueCache.getLIveWatchLogCacheName(), QueueCache.getLiveWatchLogQueue()));
        }
    }
    */
}
